package com.weactivity.service.impl;

import com.weactivity.dto.Result;
import com.weactivity.dto.ToEmail;
import com.weactivity.dto.UserDTO;
import com.weactivity.entity.Reminder;
import com.weactivity.mapper.ReminderMapper;
import com.weactivity.service.MailService;
import com.weactivity.service.RemindService;
import com.weactivity.utils.UserHolder;
import org.apache.ibatis.annotations.Select;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Service
public class RemindServiceImpl implements RemindService {

    @Autowired
    private ReminderMapper reminderMapper;

    @Value("${spring.mail.username}")
    private String from;

    @Autowired
    private MailService mailService;

    @Override
    public Result commonEmail(ToEmail toEmail) {
        //创建简单邮件消息
        SimpleMailMessage message = new SimpleMailMessage();

        //谁发的
        message.setFrom(from);
        //谁要接收
        message.setTo(toEmail.getReceivers());
        //邮件标题
        message.setSubject(toEmail.getSubject());
        //邮件内容
        message.setText(toEmail.getContent());
        try {
            mailService.sendEmail("1492918560@qq.com",from,"邮件测试");
            return Result.ok(toEmail.getReceivers());
        } catch (MailException e) {
            e.printStackTrace();
            return Result.fail("邮件发送失败");
        }

    }

    @Override
    public int insertReminder(int id, String content, String remind_time) {

        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime dateTime = LocalDateTime.parse(remind_time, dateTimeFormatter);

        UserDTO user = UserHolder.getUser();
        int uid = Math.toIntExact(user.getId());


      return  reminderMapper.insertReminder(id,uid,content,dateTime);
    }

    @Override
    public List<Reminder> showAll() {
        UserDTO user = UserHolder.getUser();

        return reminderMapper.searchAll(user.getId());

    }

    @Override
    public int deleteByid(int id) {

       return reminderMapper.deleteById(id);
    }

    /**
     * 根据提醒时间查询需要弹窗的remind
     * @return
     */
    @Override
    public List<Reminder> findNeedtoAlert() {

        LocalDateTime now = LocalDateTime.now();

       return  reminderMapper.findNeedtoAlert(now);


    }


}
